import React, { useEffect, useState, useRef } from 'react'
import QRCode from 'qrcode.react'
import alipayIcon from '@/assets/images/alipay_icon.png'
import { useModel, history, useSearchParams } from '@umijs/max'
import { ProTable } from '@ant-design/pro-components'
import subRoutes from '../../../config/subRoutes'
import copy from 'copy-to-clipboard'
import dayjs from 'dayjs'
import {
  DownloadOutlined,
  EyeTwoTone,
  EyeInvisibleTwoTone,
  UserOutlined,
  AuditOutlined,
  ExclamationCircleFilled,
  CopyOutlined,
  QuestionCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons'
import Upload from '@/components/Upload'
import {
  Space,
  InputNumber,
  Button,
  Avatar,
  Popconfirm,
  Input,
  List,
  Modal,
  Image,
  Timeline,
  Badge,
  Alert,
  Popover,
  Form,
  App,
  Tooltip,
  Card,
  Radio,
  Tag,
  Checkbox,
  Switch,
  Select,
  Table
} from 'antd'
import styles from './OrderList.less'
import { render } from 'react-dom'
import { color } from 'echarts'

const { TextArea } = Input
const OrderTypeList = {
  '/regularOrder': 0, //常规订单
  '/dealingOrder': 1, //成交订单
  '/overdueOrder': 2, //逾期订单
  '/finishedOrder': 3, //完结订单
  '/afterSaleOrder': 4, //售后订单
  '/whiteOrder': 5, //初始化订单
  '/expiredBills': 6 //到期账单
}
const depositColorMap = {
  未冻结: '#9F9F9F',
  已退还: '#3BC9C0',
  已冻结: '#4BA9FF',
  冻结转支付: '#FF7C03',
  已解冻: '#52A369'
}
const downpaymentColorMap = ['#FF5203', '#3BC9C0', '#FF0000']
const operationList = {
  已冻结: [
    {
      type: 'turnToPay',
      rules: e => e > 2100
    },
    'unFreeze'
  ],
  待分配: [
    'goApproval',
    {
      type: 'goDistribution',
      auth: 'allocate_order'
    }
  ],

  待审核: [
    'goApproval',
    {
      type: 'goDistribution',
      auth: 'allocate_order'
    }
  ],
  待售后处理: ['solveAfter'],
  归还审核: ['approvalReturn'],
  待发货: ['triggerDelivery'],
  3000: ['triggerDelivery'],
  待支付: ['editPrice']
}
const operationText = {
  // editDeposit: '修改押金',
  turnToPay: '转支付',
  unFreeze: '解冻预授权',
  refundDeposit: '退还押金',
  goApproval: '去审核',
  solveAfter: '去处理',
  approvalReturn: '归还审核',
  triggerDelivery: '发货',
  goDistribution: '分配订单',
  editPrice: '修改价格'
}
const dangerButtonList = {
  unFreeze: true,
  refundDeposit: true,
  editDeposit: true
}
const pickupInfoList = [
  {
    label: '自提点',
    parentNode: 'orderOwnTakeInfo',
    valueIndex: 'name'
  },
  {
    label: '自提地址',
    parentNode: 'orderOwnTakeInfo',
    needJoin: true,
    valueIndex: ['prov', 'city', 'area', 'detail_address']
  },
  {
    label: '收货人',
    parentNode: 'orderOwnTakeInfo',
    valueIndex: 'consignee'
  },
  {
    label: '手机号',
    parentNode: 'orderOwnTakeInfo',
    checkPrivacy: true,
    passKey: 'consignee_tel',
    valueIndex: 'tel'
  },
  {
    label: '预约提货时间',
    getValueFromEvent: data => {
      return `${data.orderOwnTakeInfo.zt_date} ${data.orderOwnTakeInfo?.zt_time?.replace('-', '至')}`
    }
  },
  {
    label: '订单编号',
    needCopy: true,
    valueIndex: 'order_sn'
  },
  {
    label: '创建时间',
    valueIndex: 'created_at'
  },
  {
    label: '订单备注',
    valueIndex: 'remarks'
  }
]

const couponMapType = {
  支付宝官方券: 'blue',
  下单立减: 'purple'
}

const payStatusMap = {
  1: {
    text: '未支付',
    color: '#000'
  },
  2: {
    text: '已支付',
    color: '#4BA9FF'
  },
  3: {
    text: '逾期支付',
    color: '#FF7D00'
  },
  4: {
    text: '已逾期',
    color: '#FF0000'
  }
}

export default () => {
  const pathname = history.location.pathname
  const sellType = pathname.includes('s_')
  const OrderType = OrderTypeList[pathname.replace('s_', '')]
  const originTabsList = [
    // 常规订单
    [
      {
        key: 'all_order',
        tab: '全部订单',
        status: '',
        num: 0
      },
      {
        key: 'wait_pay_order',
        tab: '待付款',
        status: '1000',
        num: 0
      },
      {
        key: 'wait_allocate_order',
        tab: '待分配',
        status: '2000',
        num: 0
      },
      {
        key: 'wait_audit_order',
        tab: '待审核',
        status: '2100',
        num: 0
      },
      sellType
        ? null
        : {
            key: 'wait_to_sign',
            tab: '待签约',
            status: '2200',
            num: 0
          },
      {
        key: 'wait_take_delivery',
        tab: '待提货',
        status: '2800',
        num: 0
      },
      {
        key: 'wait_shipped_order',
        tab: '待发货',
        status: '3000',
        num: 0
      },
      {
        key: 'close_order',
        tab: '订单关闭',
        status: '-1100',
        num: 0
      },
      {
        key: 'cancel_order',
        tab: '订单取消',
        status: '-1000',
        num: 0
      }
    ].filter(i => i),

    // 成交订单
    [
      {
        key: 'all_order',
        tab: '全部订单',
        status: '',
        num: 0
      },
      {
        key: 'wait_received_order',
        tab: '已发货',
        status: '3100',
        num: 0
      },
      {
        key: 'in_rent_order',
        tab: sellType ? '使用中' : '租赁中',
        status: sellType ? '4050' : '4000',
        num: 0
      },
      {
        key: 'overdue_order',
        tab: '已逾期',
        status: '4100',
        num: 0
      },
      sellType
        ? null
        : {
            key: 'performance_finished_order',
            tab: '租金完结',
            status: '4200',
            num: 0
          },
      {
        key: 'due_today',
        tab: '今日到期',
        status: '',
        become_due: 1,
        num: 0
      },
      {
        key: 'due_tomorrow',
        tab: '明日到期',
        status: '',
        become_due: 2,
        num: 0
      },
      sellType
        ? null
        : {
            key: 'due_7_day_order',
            tab: '租期结束（7日）',
            status: '4000',
            special_day_tips: '1',
            num: 0
          },
      sellType
        ? null
        : {
            key: 'wait_returned_order',
            tab: '待归还',
            status: '5000',
            num: 0
          },
      sellType
        ? null
        : {
            key: 'in_returning_order',
            tab: '归还中',
            status: '5100',
            num: 0
          },
      sellType
        ? null
        : {
            key: 'return_overdue_order',
            tab: '归还逾期',
            status: '5200',
            num: 0
          }
    ].filter(i => i),

    // 逾期订单
    [
      {
        key: 'all_order',
        tab: '全部订单',
        status: '',
        num: 0
      },
      {
        key: 'overdue_30_day_order',
        tab: '30天以内',
        status: '4100',
        special_day_tips: '2',
        num: 0
      },
      {
        key: 'overdue_30_60_day',
        tab: '30-60天',
        status: '4100',
        special_day_tips: '3',
        num: 0
      },
      {
        key: 'overdue_60_day',
        tab: '超过60天',
        special_day_tips: '4',
        status: '4100',
        num: 0
      }
    ],

    // 完结订单
    [
      {
        key: 'all_order',
        tab: '全部订单',
        status: '',
        num: 0
      },
      sellType
        ? null
        : {
            key: 'returned_order',
            tab: '已归还',
            status: '6000',
            num: 0
          },
      sellType
        ? null
        : {
            key: 'buy_out_order',
            tab: '已买断',
            status: '6100',
            num: 0
          }
    ].filter(i => i),

    // 售后订单
    [
      {
        key: 'all_order',
        tab: '全部订单',
        status: '',
        num: 0
      },
      {
        key: 'in_after_sale_order',
        tab: '待售后处理',
        status: '3000',
        in_after_sale: '1',
        num: 0
      },
      {
        key: 'after_sale_finished',
        tab: '售后完成',
        status: '9100',
        num: 0
      },
      {
        key: 'in_after_sale_close_order',
        tab: '售后拒绝',
        status: '3000',
        in_after_sale: '2',
        num: 0
      }
    ],

    // 初始化订单
    [
      {
        key: 'all_order',
        tab: '全部订单',
        status: '',
        num: 0
      }
    ],

    // 到期账单
    [
      {
        key: 'all_bill_number',
        tab: '全部订单',
        status: '0',
        num: 0
      },
      {
        key: 'paid_bill_number',
        tab: '已支付',
        status: '2',
        num: 0
      },
      {
        key: 'unpaid_bill_number',
        tab: '未支付',
        status: '1',
        num: 0
      },
      {
        key: 'late_payment_bill_number',
        tab: '逾期支付',
        status: '3',
        num: 0
      },
      {
        key: 'overdue_bill_number',
        tab: '已逾期',
        status: '4',
        num: 0
      }
    ]
  ]
  const originTabs = originTabsList[OrderType]
  const { GetShopSelections } = useModel('Goods')
  const { message, modal } = App.useApp()

  const {
    GetBackendOrderList,
    ShowPrivacy,
    OrderNumberCount,
    GetShareLinkMap,
    GetRemarkList,
    AddRemark,
    DepositThaw,
    RefundDeposit,
    DepositTransferPay,
    DeleteOrders,
    CloseOrders,
    AdminLookExpress,
    GetOverdueMoney,
    DealAfterSale,
    GetAfterSaleRejectReason,
    GetExpressCompany,
    AddExpress,
    GetAllAuditors,
    AllocateOrders,
    UpdateExpress,
    EcommerceOrderList,
    EcommerceOrderCount,
    RefundSfAmount,
    DeliveryVerify,
    GetSubShopOptions,
    GetOrderAuditors,
    AllocateToSubShop,
    WxGenerateScheme,
    OrderVoucherList,
    UnsignContractPay,
    GetListForAmendOrder,
    SubmitAmendOrder,
    AlterOrderPrice,
    GetExpiredBillsData,
    GetExpiredBillsDataCount
  } = useModel('Order')

  const { isLoading, setIsLoading, platformType, CheckOptionAuth, GetChannels, userInfo } = useModel('Global')
  const [pageSize, setPageSize] = useState(10) //  每页数量
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [shopList, setShopList] = useState([])
  const [salesManList, setSalesManList] = useState([])
  const [channelList, setChannelList] = useState([]) // 所属渠道
  const [currentChannelList, setCurrentChannelList] = useState([]) // 订单来源渠道
  const [currentOrderId, setCurrentOrderId] = useState(null)
  const [currentOrderInfo, setCurrentOrderInfo] = useState({})
  const tableRef = useRef()
  const [columns, setColumns] = useState([]) //  归属店铺
  const proTableFormRef = useRef()
  const [rowSelectable, setRowSelectable] = useState(true)

  // tab 选项卡
  const [searchParams] = useSearchParams()
  const [tabActiveKey, setTabActiveKey] = useState(() => {
    return searchParams.get('tab') || 'all_order'
  })
  const [tabsList, setTabsList] = useState([])

  // 脱敏数据
  const [privacyData, setPrivacyData] = useState({})

  // 备注弹窗
  const [showRemarkModal, setShowRemarkModal] = useState(false)
  const [remarkNote, setRemarkNote] = useState('')

  // 备注弹窗
  const [showExpressModal, setShowExpressModal] = useState(false)
  const [expressData, setExpressData] = useState({})

  // 查看备注弹窗
  const [showCheckRemarkModal, setShowCheckRemarkModal] = useState(false)
  const [remarkList, setRemarkList] = useState([])

  // 发货弹窗
  const [deliveryModal, setDeliveryModal] = useState(false)
  const [deliveryData, setDeliveryData] = useState({})

  // 物流公司列表
  const [expressList, setExpressList] = useState([])
  const [updateExpressFormRef] = Form.useForm()

  // 逾期金额展示
  const [overdueAmount, setOverdueAmount] = useState(0)

  // 去处理售后弹窗
  const [showSolveAfterModal, setShowSolveAfterModal] = useState(false)

  // 拒绝售后弹窗
  const [showRefuseAfterSalesModal, setShowRefuseAfterSalesModal] = useState(false)

  const [afterSalesModalReason, setAfterSalesModalReason] = useState('')
  const [userAfterSalesReason, setUserAfterSalesReason] = useState('')
  const [currentRefuseAfterReason, setCurrentRefuseAfterReason] = useState(null)
  const [refuseOwnAmount, setRefuseOwnAmount] = useState(null)

  // 常规订单的选择
  const [currentSelectedRowKeys, setCurrentSelectedRowKeys] = useState([])
  const [batchAllocationFlag, setBatchAllocationFlag] = useState(true)
  const [batchAllocationShow, setBatchAllocationShow] = useState(false)
  const [batchAllocationModal, setBatchAllocationModal] = useState(false)
  const [batchAllocationFormRef] = Form.useForm()
  const [allocationList, setAllocationList] = useState([])
  const [currentAuditorId, setCurrentAuditorId] = useState('')

  // 查看备注弹窗
  const [showWXNoModal, setShowWXNoModal] = useState(false)
  const [wxTradeList, setWxTradeList] = useState([])

  // 提货弹窗
  const [selfPickupFormRef] = Form.useForm()
  const [showPickupModal, setShowPickupModal] = useState(false)
  const [isView, setIsView] = useState(false)

  // 分配
  const [haveSubMerchant, setHaveSubMerchant] = useState(false)
  const [distributionModal, setDistributionModal] = useState(false)
  const [distributionList, setDistributionList] = useState([])
  const [subMerchantList, setSubMerchantList] = useState([])
  const [auditorList, setAuditorList] = useState([])
  const [distributionFormRef] = Form.useForm()

  //  优惠券信息
  const [showCouponModal, setShowCouponModal] = useState(false)
  const [couponInfo, setCouponInfo] = useState([])

  // 逾期筛选项
  const [overdueFilter, setOverdueFilter] = useState({
    sort_name: '',
    sort: ''
  })

  // 补订单
  const [refillorderForm] = Form.useForm()
  const [refillorderModal, setRefillorderModal] = useState(false)
  const [refillGainList, setRefillGainList] = useState([])
  const [refillStep, setRefillStep] = useState(0)
  const [refillQrData, setRefillQrData] = useState({})
  const [refillData, setRefillData] = useState({})
  const [gainList, setGainList] = useState([])

  // 是否去重
  const [isDistinct, setIsDistinct] = useState(false)

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 }
  }

  useEffect(() => {
    init()
  }, [])

  // 初始化
  const init = () => {
    if (platformType) {
      getAuditorSelection()
    } else {
      getShopList()
      getAllAuditorList()
    }
    getExpressList()
    getChannelList()
    if (userInfo.login_type === 'merchant') {
      checkSubMerchant()
    } else {
      setHaveSubMerchant(false)
    }
    OrderType === 2 && getOverdueAmount()
  }

  // 检查是否存在子店铺
  const checkSubMerchant = async () => {
    const res = await GetSubShopOptions({ with_main_shop: 1 })
    setShopList(res.map(i => [i.id, i.shop_name]))
    setHaveSubMerchant(res.length > 1)
  }

  // 获取审核人员列表
  const getAuditorSelection = async () => {
    const res = await GetOrderAuditors({ merchant_id: userInfo.merchant_id })
    if (res) {
      setSalesManList(res.map(i => [i.id, i.real_name]))
    }
  }

  // 获取审核人员列表
  const getAllAuditorList = async () => {
    const res = await GetAllAuditors()
    if (res) {
      setSalesManList(res.map(i => [i.id, i.real_name]))
    }
  }

  // 获取物流公司
  const getExpressList = async () => {
    const res = await GetExpressCompany()

    if (res) {
      setExpressList(
        res.map(i => ({
          ...i,
          value: `${i.label}-${i.value}`
        }))
      )
    }
  }

  // 拒绝售后
  const handleRefuseAfterSalesOK = async () => {
    const { after_sale_type } = currentOrderInfo
    if (after_sale_type === 2) {
      if (!currentRefuseAfterReason) {
        message.error('请选择拒绝原因')
        return
      } else if (currentRefuseAfterReason === 'USER_OWE_MONEY' && !refuseOwnAmount) {
        message.error('请填写欠款金额')
        return
      } else {
        const params = {
          order_id: currentOrderId,
          audit_result: 'REFUSE',
          refuse_reason_code: currentRefuseAfterReason,
          user_owe_money: refuseOwnAmount
        }

        const res = await UnsignContractPay(params)
        res && message.success('已处理')
        setCurrentRefuseAfterReason(null)
        setRefuseOwnAmount(null)
        setShowSolveAfterModal(false)
        setShowRefuseAfterSalesModal(false)
        tableRef.current.reload()
      }
    } else {
      if (!afterSalesModalReason) {
        message.error('请填写拒绝原因')
        return
      }
      let params = {
        order_id: currentOrderId,
        type: 'reject',
        reject_reason: afterSalesModalReason
      }
      const res = await DealAfterSale(params)
      res && message.success('已处理')
      setShowSolveAfterModal(false)
      setShowRefuseAfterSalesModal(false)
      tableRef.current.reload()
    }
  }

  // 同意售后
  const handleAfterSalesAgree = async () => {
    const { after_sale_type } = currentOrderInfo
    if (after_sale_type === 2) {
      const params = {
        order_id: currentOrderId,
        audit_result: 'AGREE'
      }

      const res = await UnsignContractPay(params)
      res && message.success('已处理')
    } else {
      let params = {
        order_id: currentOrderId,
        type: 'pass'
      }
      const res = await DealAfterSale(params)
      res && message.success('已处理')
    }
    setShowSolveAfterModal(false)
    tableRef.current.reload()
  }

  // 拒绝售后input
  const onInputRefuseAfterSales = e => {
    setAfterSalesModalReason(e.target.value)
  }

  const handleSelectRefuseReason = e => {
    setCurrentRefuseAfterReason(e)
  }

  // 获取逾期金额
  const getOverdueAmount = async () => {
    const params = {
      life_type: sellType ? 1 : 0
    }
    const res = await GetOverdueMoney(params)
    setOverdueAmount(res)
  }

  // 渠道列表
  const getChannelList = async () => {
    const res = await GetShareLinkMap()

    if (res) {
      let arr = [['自然流量', '自然流量'], ...res.map(i => [i.value, i.label])]
      setChannelList(arr)
    }
  }

  // 获取订单数量
  const getOrderCount = async data => {
    const res = sellType ? await EcommerceOrderCount(data) : await OrderNumberCount(data)
    formatTabs(res)
  }

  // 获取账单数量
  const getBillsCount = async data => {
    const res = await GetExpiredBillsDataCount(data)
    formatTabs(res)
  }

  //  获取店铺列表
  const getShopList = async () => {
    const res = await GetShopSelections()

    setShopList(res.map(i => [i.id, i.shop_name]))
  }

  // //  获取业务员列表
  // const getSalesmanList = async () => {
  //   const res = await GetShopSalesMan()
  //   setSalesManList(res.map(i => [i.id, i.real_name]))
  // }

  //  合并数量进tab徽标
  const formatTabs = tabsItem => {
    setTabsList(
      originTabs.map(i => ({
        key: i.key,
        tab: (
          <Badge
            showZero
            key={i.key}
            count={tabsItem[i.key]}
            overflowCount={99999}
            style={{
              position: 'relative',
              top: '5px',
              margin: '0 5px',
              padding: '3px 8px',
              boxSizing: 'border-box',
              borderRadius: '15px',
              fontSize: '14px',
              backgroundColor: tabActiveKey === i.key ? '#EAF7FF' : '#F0F0F0',
              color: tabActiveKey === i.key ? '#548FFB' : '#838383'
            }}
          >
            <span>{i.tab}</span>
          </Badge>
        )
      }))
    )
  }

  // 处理 tab 切换
  const handleTabActive = key => {
    setTabActiveKey(key)

    // 待审核,显示批量分配按钮
    setBatchAllocationShow(
      (key === 'wait_audit_order' || key === 'wait_allocate_order') &&
        platformType === 1 &&
        CheckOptionAuth('allocate_order')
    )
    setBatchAllocationFlag(true)

    setCurrentPage(1)

    tableRef.current.reload()
  }

  // 查看用户信息
  const checkUser = id => {
    window.open(`/cashpledge?id=${id}`)
  }

  // 跳转商品页
  const goProduct = (type, id, merchant_id) => {
    // todo 区分平台端和商家端
    let url = `/product?type=${type}&id=${id}&merchant_id=${merchant_id}`
    window.open(url)
  }

  // 查看订单详情
  const checkOrderDetail = id => {
    const url = `/orderInfo/${id}`
    window.open(url)
  }

  // 切换脱敏状态
  const triggerPrivacy = async (orderId, type, showFlag, refreshCurrent) => {
    const newPrivacyData = { ...privacyData }
    const dataItem = newPrivacyData[orderId]
    if (showFlag) {
      const params = {
        order_id: orderId,
        type
      }
      const res = await ShowPrivacy(params)
      if (res) {
        newPrivacyData[orderId] = {
          ...(dataItem || {}),
          [`show_${type}`]: showFlag,
          [type]: res
        }
        setPrivacyData(newPrivacyData)
        if (refreshCurrent) {
          setCurrentOrderInfo({
            ...currentOrderInfo,
            [`show_${type}`]: showFlag,
            [type]: res
          })
        }
        tableRef.current.reload()
      }
    } else {
      newPrivacyData[orderId] = {
        ...(dataItem || {}),
        [`show_${type}`]: showFlag
      }
      delete newPrivacyData[orderId][type]

      if (refreshCurrent) {
        const data = { ...currentOrderInfo }
        delete data[`show_${type}`]
        delete data[type]

        setCurrentOrderInfo(data)
      }

      setPrivacyData(newPrivacyData)
      tableRef.current.reload()
    }
  }

  // 备注弹窗开关
  const triggerRemark = (id, remarks = null) => {
    id && setCurrentOrderId(id)
    setRemarkNote(remarks)
    setShowRemarkModal(!showRemarkModal)
  }

  // 输入备注
  const onInputRemark = e => {
    setRemarkNote(e.target.value)
  }

  // 确认备注
  const handleRemarkOk = async () => {
    const res = await AddRemark({
      id: currentOrderId,
      content: remarkNote
    })
    if (res) {
      setRemarkNote('')
      setCurrentOrderId(null)
      triggerRemark()
      tableRef.current.reload()
    }
  }

  // 查询备注信息
  const checkRemark = async id => {
    setIsLoading(true)
    const res = await GetRemarkList({ id })
    setIsLoading(false)
    if (res) {
      setRemarkList(res)
      setShowCheckRemarkModal(true)
    }
  }

  //  表格中带有操作函数的处理函数
  const handleOptionWithMethod = async (method, id, isNormalMethod) => {
    if (isNormalMethod) {
      method(id)
    } else {
      setIsLoading(true)
      await method({ order_id: id })
      setIsLoading(false)
      tableRef.current.reload()
    }
  }

  //  增值服务转入
  const handleGainPay = async id => {
    setIsLoading(true)
    await DepositTransferPay({ order_id: id, type: 2 })
    setIsLoading(false)
    tableRef.current.reload()
  }

  //  修改押金弹窗
  const triggerEditDeposit = record => {
    console.log('修改押金弹窗')
    const { id, order_deposit } = record
    setCurrentOrderId(id)
  }

  //  查看物流信息
  const checkExpress = async (type, id) => {
    const res = await AdminLookExpress({ type, id })
    if (res) {
      res.timeLine = res.track.data.map(i => ({
        label: i.time,
        children: i.context
      }))
      setExpressData(res)
      setShowExpressModal(true)
    }
  }

  //  去处理弹窗
  const triggerSolveAfter = async e => {
    setCurrentOrderId(e.id)
    const res = await GetAfterSaleRejectReason({
      id: e.id
    })
    setUserAfterSalesReason(res)
    setCurrentOrderInfo(e)

    setShowSolveAfterModal(true)
  }

  //  归还审核弹窗
  const triggerApprovalReturn = () => {}

  //  跳转处理
  const handleNavigate = (type, id) => {
    switch (type) {
      case 'bill':
        window.open(`/billingDetails/${id}`)
        break
      case 'goApproval':
        checkOrderDetail(id)
        break
    }
  }

  //表格中不带有操作函数的处理函数
  const handleOption = (type, record) => {
    const typeList = {
      editDeposit: {
        type: 'modal',
        method: triggerEditDeposit
      }, // 修改押金
      goApproval: {
        type: 'navigate',
        method: handleNavigate
      },
      // 修改价格
      editPrice: {
        type: 'modal',
        method: handleEditPrice
      },
      //去审核
      solveAfter: {
        type: 'modal',
        method: triggerSolveAfter
      }, //去处理
      approvalReturn: {
        type: 'modal',
        method: triggerApprovalReturn
      }, //待发货
      triggerDelivery: {
        type: 'modal',
        method: triggerDelivery
      },
      goDistribution: {
        type: 'modal',
        method: goDistribution
      }
    }

    const item = typeList[type]
    if (item.type === 'modal') {
      item.method(record)
    } else if (item.type === 'navigate') {
      item.method(type, record.id)
    }
  }

  // 发货弹窗
  const triggerDelivery = data => {
    if (data && data.id) {
      setCurrentOrderId(data.id)
    } else {
      setCurrentOrderId(null)
    }
    setDeliveryModal(!deliveryModal)
    if (deliveryModal) {
      setDeliveryData({})
    }
  }

  // 填写发货信息
  const changeDeliveryData = (key, value) => {
    const data = { ...deliveryData }
    data[key] = value
    setDeliveryData(data)
  }

  // 发货
  const handleDelivery = async () => {
    const { expressName, expressNo } = deliveryData
    if (!expressName || !expressNo) {
      message.warning('请完善发货信息')
    } else {
      const [company_name, company] = expressName.split('-')
      const params = {
        company_name,
        company,
        id: currentOrderId,
        number: expressNo
      }
      const res = await AddExpress(params)
      if (res) {
        message.success('发货成功')
        triggerDelivery()
        tableRef.current.reload()
      }
    }
  }

  //  渲染表格中操作项
  const renderOption = (type, record, checkStatus) => {
    if (platformType) {
      const { id } = record
      const optList = operationList[type] ? operationList[type] : checkStatus ? operationList[record.status] || [] : []
      // 部分操作对照表
      const optionMap = {
        // 转支付
        turnToPay: {
          needPop: true,
          method: DepositTransferPay
        },
        // 解冻
        unFreeze: {
          needPop: true,
          method: DepositThaw
        },
        // 退还押金
        refundDeposit: {
          needPop: true,
          method: RefundDeposit
        },
        // 去审核
        goApproval: {
          needPop: haveSubMerchant,
          isNormalMethod: true,
          title: '不分配直接进入审核',
          iconColor: '#165DFF',
          description: '选择直接审核将直接分配给当前账号直接进入审核流程，归属为当前账号及所属店铺，是否确定继续？',
          method: checkOrderDetail
        },
        // 修改价格
        editPrice: {
          needPop: false
        },
        // 修改押金
        editDeposit: {
          needPop: false
        },
        // 去处理
        solveAfter: {
          needPop: false
        },
        // // 归还审核
        // 'approvalReturn': {
        //   needPop: false,
        //   method: todo
        // },
        // 发货
        triggerDelivery: {
          needPop: false
        },
        // 去分配
        goDistribution: {
          needPop: false,
          checkAuth: true,
          auth: haveSubMerchant
        }
      }

      const btnStyleMap = {
        goDistribution: { background: '#3BC9C0' }
      }

      return optList.length ? (
        <Space>
          {optList.map(optItem => {
            let i = optItem
            if (typeof optItem !== 'string') {
              if (optItem.rules && optItem.rules(record.status)) {
                i = optItem.type
              } else if (optItem.auth && CheckOptionAuth(optItem.auth)) {
                i = optItem.type
              } else {
                return null
              }
            }

            const optionItem = optionMap[i]

            if (optionItem) {
              const { needPop, method, checkAuth, auth, isNormalMethod, title, description, iconColor } = optionItem

              return needPop ? (
                <Popconfirm
                  key={i}
                  title={title || `是否确认${operationText[i]}？`}
                  icon={<ExclamationCircleFilled style={{ color: iconColor }} />}
                  description={description || ''}
                  onConfirm={() => handleOptionWithMethod(method, id, isNormalMethod)}
                  okText='确认'
                  cancelText='取消'
                >
                  <Button key={i} className={styles.inner_option_button} type='primary' danger={dangerButtonList[i]}>
                    {operationText[i]}
                  </Button>
                </Popconfirm>
              ) : !checkAuth || auth ? (
                <Button
                  key={i}
                  className={styles.inner_option_button}
                  type='primary'
                  danger={dangerButtonList[i]}
                  style={btnStyleMap[i] || {}}
                  onClick={() => handleOption(i, record)}
                >
                  {operationText[i]}
                </Button>
              ) : null
            } else {
              return (
                <Button
                  key={i}
                  className={styles.inner_option_button}
                  type='primary'
                  danger={dangerButtonList[i]}
                  style={btnStyleMap[i] || {}}
                  onClick={() => handleOption(i, record)}
                >
                  {operationText[i]}
                </Button>
              )
            }
          })}
        </Space>
      ) : null
    } else {
      return null
    }
  }

  //  关闭订单
  const handleCloseOrder = async id => {
    await CloseOrders({ order_id: id })
    message.success('操作成功')
    tableRef.current.reload()
  }

  //  电商退款
  const handleRefund = async id => {
    await RefundSfAmount({ order_id: id })
    message.success('操作成功')
    tableRef.current.reload()
  }

  //  删除订单
  const handleDeletOrder = async id => {
    await DeleteOrders({ order_id: id })
    message.success('操作成功')
    tableRef.current.reload()
  }

  // 常规订单选中
  const handleSelectChange = (selectedRowKeys, selectedRows) => {
    if (selectedRowKeys.length === 0) {
      // console.log('未选中');
      setBatchAllocationFlag(true)
    } else {
      // console.log('选中');
      setBatchAllocationFlag(false)
    }
    setCurrentSelectedRowKeys(selectedRowKeys)
  }

  // 批量分配弹窗确认
  const handleConfirmBatchAllocation = () => {
    batchAllocationFormRef.submit()
  }

  // 批量分配提交事件
  const onForceAFinished = async () => {
    let params = {
      to_user_id: currentAuditorId,
      order_ids: currentSelectedRowKeys
    }
    const res = await AllocateOrders(params)
    if (res) {
      setBatchAllocationModal(false)
      message.success('分配成功')
      tableRef.current.reload()
    }
  }

  // 获取批量分配人员名单
  const getBatchAllocationList = async () => {
    const res = await GetOrderAuditors({ merchant_id: userInfo.merchant_id })
    if (res) {
      let tempOptions = res.map(item => {
        return {
          label: item.real_name,
          value: item.id
        }
      })
      setAllocationList(tempOptions)
      setBatchAllocationModal(true)
    }
  }

  // 更改批量分配人员名单选择项
  const checkAllocation = id => {
    setCurrentAuditorId(id)
  }

  // 查看微信订单编号
  const checkWXNo = list => {
    setShowWXNoModal(true)
    setWxTradeList(list)
  }

  // 修改物流
  const handleUpdateExpress = async row => {
    modal.confirm({
      title: '修改物流',
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          <Form preserve={false} form={updateExpressFormRef} layout='vertical' name='updateExpressForm'>
            <Form.Item name='expressList' label='快递公司 : ' rules={[{ required: true, message: '请选择快递公司' }]}>
              <Select options={expressList} placeholder={'请选择快递公司'} />
            </Form.Item>

            <Form.Item name='expressNo' label='快递单号 : ' rules={[{ required: true, message: '请输入快递单号' }]}>
              <Input placeholder={'请输入快递单号'} />
            </Form.Item>
          </Form>
        </div>
      ),
      okText: '确认修改',
      onOk: async () => {
        await updateExpressFormRef.validateFields()
        const { expressList, expressNo } = updateExpressFormRef.getFieldsValue()
        let [company_name, company] = expressList.split('-')

        let params = {
          id: row.id,
          number: expressNo,
          company_name,
          company
        }

        await UpdateExpress(params)
        message.success('修改成功')
        tableRef.current.reload()
      }
    })
  }

  useEffect(() => {
    getCurrentChannel()
  }, [])

  useEffect(() => {
    if (OrderType === 6) {
      setRowSelectable(false)
    } else {
      setRowSelectable(true)
    }
  }, [OrderType])

  // 获取当前渠道
  const getCurrentChannel = async () => {
    let res = await GetChannels()
    let arr = []

    let obj = {
      'mp-alipay': '1',
      'mp-weixin': '2',
      app: '3',
      h5: '4'
    }

    if (res) {
      res.forEach(item => {
        arr.push([obj[item.label], item.name])
      })
      setCurrentChannelList(arr)
    }
  }

  const handleSelfPickup = (data, isView) => {
    setCurrentOrderInfo(data)
    if (isView) {
      const initialValues = {
        code: data.code,
        voucher: data.voucher || []
      }
      selfPickupFormRef.setFieldsValue(initialValues)
    }
    setShowPickupModal(true)
    setIsView(isView)
  }

  const copyToClip = data => {
    copy(data)
    message.success('复制成功')
  }

  const handleSubmitPickup = async e => {
    const params = {
      id: currentOrderInfo.id,
      user_id: currentOrderInfo.user_id,
      ...e
    }

    const res = await DeliveryVerify(params)
    if (res) {
      message.success('验证成功')
      setShowPickupModal(false)
      tableRef.current.reload()
    }
  }

  const checkPickup = () => {
    selfPickupFormRef.submit()
  }

  const formatUploadValue = e => {
    return e.map(i => i.value)
  }

  const getSubMerchantList = async () => {
    const res = await GetSubShopOptions({ with_main_shop: 1 })
    setSubMerchantList(res.map(i => ({ label: i.shop_name, value: i.id })))
  }

  const getAuditorsList = async merchant_id => {
    const res = await GetOrderAuditors({ merchant_id })
    setAuditorList(res.map(i => ({ label: i.real_name, value: i.id })))
  }

  // 批量分配
  const batchDistribution = () => {
    setDistributionList([...currentSelectedRowKeys])
    getSubMerchantList()
    setDistributionModal(true)
  }

  // 去分配
  const goDistribution = data => {
    setDistributionList([data.id])
    getSubMerchantList()
    setDistributionModal(true)
  }

  const handleSelectSubMerchant = id => {
    getAuditorsList(id)
  }

  const handleDistribute = async data => {
    const res = await AllocateToSubShop({ ...data, order_ids: distributionList })
    if (res) {
      message.success('分配成功')
      setDistributionModal(false)
      tableRef.current.reload()
    }
  }

  const generateLink = async sn => {
    const res = await WxGenerateScheme({
      path: `/pages/index/confirmOrder/confirmOrder`,
      query: `id=${sn}&isThridPay=1`
    })
    copy(res)
    message.success('签约链接已复制至剪贴板')
  }

  // 去重
  const onIsDistinctSwitchChange = () => {
    setIsDistinct(!isDistinct)
    tableRef.current.reload()
  }

  // 优惠券相关-----------
  const triggerCouponModal = async data => {
    setCurrentOrderInfo(data)
    const res = await OrderVoucherList({ order_id: data.id })
    if (res && res.coupon_list) {
      setCouponInfo(res.coupon_list)
    }
    setShowCouponModal(true)
  }
  // 优惠券相关-----------

  // 补订单-----------
  const handleRefillChange = e => {
    setRefillGainList(e)
  }

  const handleChangeRefillOrderPrice = (id, value) => {
    console.log('refillorderForm', id, value)
    setRefillData({
      ...refillData,
      [id]: value
    })
  }

  const handleRefillOrder = async data => {
    setIsLoading(true)
    const list = await GetListForAmendOrder()
    setCurrentOrderId(data.id)
    setCurrentOrderInfo(data)
    setGainList(list)
    setIsLoading(false)
    setRefillorderModal(true)
  }

  const generateQr = async () => {
    const value = await refillorderForm.validateFields()

    const params = {
      order_id: currentOrderId,
      gain_info: value.id.map(i => {
        let gain = { id: i }
        if (refillData[i]) {
          gain.val = refillData[i]
        }
        return gain
      })
    }
    const res = await SubmitAmendOrder(params)
    if (res) {
      setRefillQrData(res)
      setRefillStep(1)
      tableRef.current.reload()
    }
  }

  const downloadQr = () => {
    const link = document.createElement('a')
    link.href = document.getElementById('qrCode').toDataURL('image/png')
    link.download = 'qrcode.png'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  const cancelRefillorder = () => {
    setRefillorderModal(false)
    setRefillStep(0)
    setRefillQrData({})
    setRefillData({})
  }
  // 补订单-----------

  // 导出数据---------------
  const handleExportTable = async () => {
    // 获取当前路由菜单名称
    const routerName = subRoutes.filter(item => item.path.match(location.pathname))?.[0]?.name

    const params = proTableFormRef.current.getFieldsValue()

    let filter = {
      plat_from_source: params.plat_from_source,
      use_rec_name: params.use_rec_name,
      tel: params.tel,
      merchant_id: params.merchant_id,
      order_sn: params.order_sn,
      belong_mer_sale: params.belong_mer_sale,
      order_source: params.order_source,
      is_repurchase: params.is_repurchase,
      created_at_start:
        params.created_date &&
        params.created_date.length &&
        dayjs(params.created_date[0]['$d']).format('YYYY-MM-DD HH:mm:ss'),
      created_at_end:
        params.created_date &&
        params.created_date.length &&
        dayjs(params.created_date[1]['$d']).format('YYYY-MM-DD HH:mm:ss'),
      type: OrderType,
      platform_type: platformType ? 2 : 1,

      channel_type: 'e_card', // single:独立部署    saas:saas项目  green:绿植项目  e_card:E卡项目
      platform_id: userInfo.pf_id,
      admin_user_id: userInfo.id,
      login_type: userInfo.login_type,
      route_menu_name: (sellType ? '电商订单_' : '租赁订单_') + routerName,
      life_type: sellType ? 1 : 0 // 0  租赁订单  1 电商订单
    }

    if (tabActiveKey && tabActiveKey !== 'all_order') {
      const item = originTabs.find(i => i.key === tabActiveKey)
      filter.status = item.status
      filter.special_day_tips = item.special_day_tips
      filter.in_after_sale = item.in_after_sale
      filter.become_due = item.become_due
    }

    const res = await request('https://msg.weizu777.cn/api/orderExport', {
      method: 'GET',
      params: filter,
      hideNotice: false
    })

    if (res) {
      message.success('数据导出成功，请在顶部导航【导出中心】下载内容')
    }
  }
  // 导出数据---------------

  const [editPriceFormRef] = Form.useForm()

  const editPriceColumns = [
    {
      title: '商品',
      key: 'goods_name',
      dataIndex: 'goods_name',
      width: 300,
      render: (text, record) => (
        <Space>
          <Image width={72} src={record.goods_pic} />
          <div>
            <div>
              <a onClick={() => goProduct(3, record.goods_id, record.merchant_id)}>{text}</a>
            </div>
            <span>套餐：{record.attr_value}</span>
          </div>
        </Space>
      )
    },
    {
      title: '订单原价',
      key: sellType ? 'buyout_amount' : 'total_price',
      dataIndex: sellType ? 'buyout_amount' : 'total_price',
      hideInSearch: true,
      width: 220,
      render: (text, record) => {
        const {
          balance_payment,
          current_buyout_amount,
          lease_term,
          status,
          received_amount,
          id,
          life_type,
          total_price,
          mature_buyout_payment
        } = record
        return sellType ? (
          <>
            <div>
              <b>
                购买价：¥{text}（{lease_term}期）
              </b>
            </div>

            <div>
              <b>每期租金¥{(text / lease_term).toFixed(2)}</b>
            </div>

            <div>
              当前尾款：¥<b>{balance_payment}</b>
            </div>
          </>
        ) : (
          <>
            <div>
              <b>
                总租金：¥{text}（{lease_term}期）
              </b>
            </div>

            <div>
              <b>每期租金¥{(text / lease_term).toFixed(2)}</b>
            </div>

            {life_type === 2 ? null : (
              <div>
                到期买断款：¥<b>{mature_buyout_payment}</b>
              </div>
            )}
          </>
        )
      }
    },
    {
      title: '优惠信息',
      key: 'total_discount_amount',
      dataIndex: 'total_discount_amount',
      hideInSearch: true,
      width: 300,
      render: (text, record) => (
        <>
          {record.discount_type_list && record.discount_type_list.length ? (
            <>
              <div>
                {record.discount_type_list.map(i => (
                  <Tag key={i} color={'#F5319D'}>
                    {i}
                  </Tag>
                ))}
              </div>
              <div style={{ marginTop: '10px', color: '#F5319D' }}>优惠总额：-￥{record.total_discount_amount}</div>
              <div style={{ marginTop: '10px' }}>
                <Button size='small' type='primary' onClick={() => triggerCouponModal(record)}>
                  优惠券信息
                </Button>
              </div>
            </>
          ) : (
            <div>
              <Tag>未使用</Tag>
            </div>
          )}
        </>
      )
    },
    {
      title: '修改价格',
      dataIndex: 'edit_price',
      key: 'edit_price',
      width: 300,
      render: (text, record) => (
        <Form
          style={{
            position: 'relative'
          }}
          initialValues={{
            moneyType: 1,
            editPrice: 1
          }}
          name='editPriceForm'
          form={editPriceFormRef}
        >
          <Form.Item label='' noStyle name='moneyType'>
            <Radio.Group>
              <Radio value={1}>总租金/购买价减少</Radio>
              <Radio value={2}>总租金/购买价涨价</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label='修改价格'
            name='editPrice'
            rules={[
              { required: true, message: '请输入修改价格' },
              { pattern: /^[1-9]\d*$/, message: '请输入正整数' }
            ]}
          >
            <InputNumber prefix='¥' size='small' min={1} />
          </Form.Item>

          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const moneyType = getFieldValue('moneyType')
              const editPrice = getFieldValue('editPrice')

              const totalPrice = sellType ? record.buyout_amount : record.total_price

              return (
                <div className={styles.edit_price_detail_content}>
                  <div style={{ fontWeight: 600 }}>修改后的价格:</div>

                  <div style={{ whiteSpace: 'nowrap' }}>
                    <Tooltip placement='topLeft' title={'计价方式：原价 +  修改价格（涨价或优惠） '}>
                      <span style={{ color: '#7A8394' }}>
                        {' '}
                        总租金/购买价 <InfoCircleOutlined /> :{' '}
                      </span>
                    </Tooltip>

                    <span style={{ color: '#333', fontWeight: '600' }}>¥{totalPrice}</span>

                    <span style={{ color: '#7B61FF', fontWeight: '600' }}>
                      {moneyType === 1 ? <>-¥{editPrice}</> : <>+¥{editPrice}</>}
                    </span>

                    <span style={{ color: '#f00', fontWeight: '600' }}>
                      =¥
                      {moneyType === 1
                        ? (Number(totalPrice) - Number(editPrice)).toFixed(2)
                        : (Number(totalPrice) + Number(editPrice)).toFixed(2)}
                    </span>
                  </div>

                  <div
                    style={{
                      whiteSpace: 'nowrap',
                      display: 'flex',
                      alignItems: 'center'
                    }}
                  >
                    <span style={{ color: '#7A8394' }}>每期金额 : </span>
                    <span>
                      ¥
                      {moneyType === 1
                        ? ((Number(totalPrice) - Number(editPrice)) / Number(record.lease_term)).toFixed(2)
                        : ((Number(totalPrice) + Number(editPrice)) / Number(record.lease_term)).toFixed(2)}
                    </span>
                    <span
                      style={{
                        display: 'flex',
                        alignItems: 'center'
                      }}
                    >
                      (<span style={{ color: '#7A8394' }}>较原价</span>
                      <svg className='icon' aria-hidden='true' style={{ width: '20px', height: '20px' }}>
                        {moneyType === 1 ? (
                          <use xlinkHref={'#icon-bailongdown'}></use>
                        ) : (
                          <use xlinkHref={'#icon-bailongup'}></use>
                        )}
                      </svg>
                      {moneyType === 1 ? (
                        <span style={{ color: '#3CC759' }}>{`${(
                          ((Number(totalPrice) - Number(editPrice)) / Number(totalPrice)) *
                          100
                        ).toFixed(2)}%`}</span>
                      ) : (
                        <span style={{ color: '#f00' }}>{`${(
                          ((Number(totalPrice) + Number(editPrice)) / Number(totalPrice)) *
                          100
                        ).toFixed(2)}%`}</span>
                      )}
                      )
                    </span>
                  </div>

                  <div style={{ whiteSpace: 'nowrap' }}>
                    <span style={{ color: '#7A8394' }}>到期买断款 : </span>
                    {record?.mature_buyout_payment ? <span>¥{record.mature_buyout_payment}</span> : '--'}
                  </div>
                </div>
              )
            }}
          </Form.Item>
        </Form>
      )
    }
  ]

  const EditPriceCom = ({ data }) => {
    return (
      <div>
        <Alert type='warning' message='注：协议支付规定不允许超出官网价1.3倍' />

        <div className={styles.edit_price_info}>
          <Space>
            <span className={styles.edit_price_label}>收货人 :</span>
            <span>{data.use_rec_name || '-'}</span>
          </Space>
          <Space>
            <span className={styles.edit_price_label}>联系电话 :</span>
            <span>
              {`${data.mobile} ` || '未获取手机号'}
              {data.mobile ? (
                data.show_mobile ? (
                  <EyeInvisibleTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(data.id, 'mobile')}
                  />
                ) : (
                  <EyeTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(data.id, 'mobile', true)}
                  />
                )
              ) : null}
            </span>
          </Space>
          <Space>
            <span className={styles.edit_price_label}>收货地址 :</span>
            <span>{data.address || '-'}</span>
          </Space>
          <Space>
            <span className={styles.edit_price_label}>下单备注 :</span>
            <span>{data.buyer_remark || '-'}</span>
          </Space>
        </div>

        <Table
          pagination={false}
          columns={editPriceColumns}
          dataSource={[
            {
              key: data.id,
              ...data
            }
          ]}
        />

        <div className={styles.edit_price_detail}></div>
      </div>
    )
  }

  // 修改价格
  const handleEditPrice = async data => {
    const configEvent = async () => {
      //   // 获取表单数据
      await editPriceFormRef.validateFields()
      const { moneyType, editPrice } = editPriceFormRef.getFieldsValue()

      const params = {
        order_id: data.id,
        type: moneyType,
        amount: editPrice
      }

      const res = await AlterOrderPrice(params)
      if (res) {
        message.success('价格修改成功')
        tableRef.current.reload()
        Modal.destroyAll()
      }
    }

    modal.confirm({
      title: '修改价格',
      icon: null,
      width: '70%',
      content: <EditPriceCom data={data} />,
      footer: options => {
        return (
          <div>
            <Button key='back' onClick={() => Modal.destroyAll()} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Popconfirm
              title='确认修改后将按照新的租金生效，是否确认修改？'
              description={<span style={{ color: '#F55107' }}>（注：协议支付规定不允许超出官网价1.3倍）</span>}
              onConfirm={configEvent}
              okText='确认'
              cancelText='取消'
            >
              <Button key='submit' type='primary' style={{ marginRight: 10 }}>
                确认修改
              </Button>
            </Popconfirm>
          </div>
        )
      }
    })
  }

  const originColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
      width: 60
    },
    {
      title: '订单信息',
      dataIndex: 'order_sn',
      hideInSearch: true,
      width: 300,
      render: (text, record) => (
        <>
          <div className={styles.order_tag_group}>
            {record.life_type === 2 ? (
              <div>
                <Tag color='green'>自建订单</Tag>
              </div>
            ) : (
              <div>
                <Tag color='blue'>普通订单</Tag>
              </div>
            )}

            {record.xz_flag === 1 && (
              <div>
                <Tag color='purple'>续租</Tag>
              </div>
            )}

            {!!record.is_notary && (
              <div>
                <Tag color='red'>已公证</Tag>
              </div>
            )}
          </div>

          <div>
            <b>订单编号：{text}</b>
          </div>
          <div>下单时间：{record.created_at}</div>
          {record.xz_flag === 1 && (
            <div
              style={{ color: '#1677ff', cursor: 'pointer' }}
              onClick={() => checkOrderDetail(record.original_order_id)}
            >
              原订单 : {record.original_no}
            </div>
          )}
        </>
      )
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      hideInSearch: true,
      width: 300,
      render: (text, record) => (
        <Space>
          <Image width={72} src={record.goods_pic} />
          <div>
            <div>
              <a onClick={() => goProduct(3, record.goods_id, record.merchant_id)}>{text}</a>
            </div>
            <span>套餐：{record.attr_value}</span>
          </div>
        </Space>
      )
    },
    {
      title: '用户资料',
      dataIndex: 'cert_name',
      hideInSearch: true,
      width: 280,
      render: (text, record) => {
        const { cert_no, user_id, gender, age, face_identify, mobile, show_cert_no, show_mobile, id } = record

        return (
          <>
            {text && cert_no ? (
              <div>
                <b>
                  {text}（{cert_no}）
                </b>
                {show_cert_no ? (
                  <EyeInvisibleTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(id, 'cert_no')}
                  />
                ) : (
                  <EyeTwoTone className={styles.clickable_icon} onClick={() => triggerPrivacy(id, 'cert_no', true)} />
                )}
              </div>
            ) : (
              <p className={styles.grey}>未实名认证</p>
            )}
            <div>
              <b>
                用户ID：
                <a onClick={e => checkUser(user_id)}>{user_id}</a>
              </b>
            </div>
            <div>
              <span>
                <span>{gender && age ? `${gender}（${age}岁）  ` : `-   `}</span>
                人脸识别：
                <svg className='icon' aria-hidden='true'>
                  <use xlinkHref={face_identify ? '#icon-bailongsuccessful' : '#icon-bailongfailed'}></use>
                </svg>
              </span>
            </div>
            <div>
              {`${mobile} ` || '未获取手机号'}
              {mobile ? (
                show_mobile ? (
                  <EyeInvisibleTwoTone className={styles.clickable_icon} onClick={() => triggerPrivacy(id, 'mobile')} />
                ) : (
                  <EyeTwoTone className={styles.clickable_icon} onClick={() => triggerPrivacy(id, 'mobile', true)} />
                )
              ) : null}
            </div>
          </>
        )
      }
    },
    {
      title: '收货信息',
      dataIndex: 'address',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const {
          use_rec_tel,
          show_use_rec_tel,
          use_rec_name,
          delivery_method,
          orderOwnTakeInfo,
          consignee_tel,
          show_consignee_tel,
          id
        } = record
        return delivery_method ? (
          <>
            <div style={{ color: '#FF5203' }}>配送方式：上门自提</div>
            <div>自提点：{orderOwnTakeInfo.name}</div>
            <div>预约时间：{`${orderOwnTakeInfo.zt_date} ${orderOwnTakeInfo?.zt_time?.replace('-', '至')}`}</div>
            <div>收货人：{orderOwnTakeInfo.consignee}</div>
            <div>
              手机：{consignee_tel || orderOwnTakeInfo.tel || '-'}
              {orderOwnTakeInfo.tel ? (
                show_consignee_tel ? (
                  <EyeInvisibleTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(id, 'consignee_tel')}
                  />
                ) : (
                  <EyeTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(id, 'consignee_tel', true)}
                  />
                )
              ) : null}
            </div>
          </>
        ) : (
          <>
            <div style={{ color: '#165DFF' }}>配送方式：快递发货</div>
            <div>收货地址：{text || '-'}</div>
            <div>收货人：{use_rec_name || '-'}</div>
            <div>
              手机：{use_rec_tel || '-'}
              {use_rec_tel ? (
                show_use_rec_tel ? (
                  <EyeInvisibleTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(id, 'use_rec_tel')}
                  />
                ) : (
                  <EyeTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(id, 'use_rec_tel', true)}
                  />
                )
              ) : null}
            </div>
          </>
        )
      }
    },
    {
      title: sellType ? '首付款' : '信用金额',
      dataIndex: sellType ? 'downpayment' : 'xy_new_amount',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const {
          id,
          downpayment_status,
          downpayment_status_desc,
          pay_amount,
          deduction_amount,
          order_deposit_status,
          order_deposit_balance,
          own_actual_paid,
          credit_reduce_amount,
          rest_fund_amoun,
          xy_total_gain_amount,
          xy_new_fund_amount,
          xy_new_credit_amount,
          xy_new_residue_freeze_amount
        } = record

        return sellType ? (
          <>
            <div>
              <b>首付款：¥{text}</b>
            </div>
            <div>
              实付：¥{pay_amount} (商家减免：-¥{deduction_amount} )
            </div>
            <div style={{ color: downpaymentColorMap[downpayment_status] }}>
              <b>首付款状态：{downpayment_status_desc}</b>
            </div>
          </>
        ) : (
          <>
            <div>
              实际冻结：¥{xy_new_fund_amount} (信用免押：-¥{xy_new_credit_amount} )
            </div>
            <div style={{ color: '#1677ff' }}>信用冻结余额：¥{xy_new_residue_freeze_amount}</div>
            {renderOption(order_deposit_status, record)}
          </>
        )
      }
    },
    {
      title: sellType ? '账单信息' : '租金账单',
      dataIndex: sellType ? 'buyout_amount' : 'total_price',
      hideInSearch: true,
      width: 220,
      render: (text, record) => {
        const { balance_payment, current_buyout_amount, lease_term, status, received_amount, id, life_type } = record
        return sellType ? (
          <>
            <div>
              <b>
                购买价：¥{text}（{lease_term}期）
              </b>
            </div>
            <div>
              当前尾款：¥<b>{balance_payment}</b>
            </div>
            <div>
              {/* 待支付 1000 待审核 2100 订单取消 -1000 订单关闭 -1100*/}
              {status !== 1000 && status !== 2100 && status !== -1100 && status !== -1000 ? (
                <Space>
                  <div className={styles.already_received_amount_text}>已收：¥{received_amount}</div>
                  <Button
                    type='primary'
                    className={[styles.inner_option_button, styles.option_aqua_button]}
                    onClick={() => handleNavigate('bill', id)}
                  >
                    账单
                  </Button>
                </Space>
              ) : null}
            </div>
          </>
        ) : (
          <>
            <div>
              <b>
                总租金：¥{text}（{lease_term}期）
              </b>
            </div>

            {life_type === 2 ? null : (
              <div>
                当前买断款：¥<b>{current_buyout_amount}</b>
              </div>
            )}

            <div>
              {/* 待支付 1000 待审核 2100 订单取消 -1000 订单关闭 -1100*/}
              {status !== 1000 && status !== 2100 && status !== -1100 && status !== -1000 ? (
                <Space>
                  <div className={styles.already_received_amount_text}>已收：¥{received_amount}</div>
                  <Button
                    type='primary'
                    className={[styles.inner_option_button, styles.option_aqua_button]}
                    onClick={() => handleNavigate('bill', id)}
                  >
                    账单
                  </Button>
                </Space>
              ) : null}
            </div>
          </>
        )
      }
    },
    {
      title: '优惠信息',
      dataIndex: 'total_discount_amount',
      hideInSearch: true,
      width: 300,
      render: (text, record) => (
        <>
          {record.discount_type_list && record.discount_type_list.length ? (
            <>
              <div>
                {record.discount_type_list.map(i => (
                  <Tag key={i} color={couponMapType[i]}>
                    {i}
                  </Tag>
                ))}
              </div>
              <div style={{ marginTop: '10px', color: '#722ED1' }}>优惠总额：-￥{record.total_discount_amount}</div>
              <div style={{ marginTop: '10px' }}>
                <Button size='small' type='primary' onClick={() => triggerCouponModal(record)}>
                  优惠券信息
                </Button>
              </div>
            </>
          ) : (
            <div>
              <Tag>未使用</Tag>
            </div>
          )}
        </>
      )
    },
    {
      title: '订单状态',
      dataIndex: 'status_desc',
      hideInSearch: true,
      width: OrderType ? 280 : 140,
      // 订单逾期筛选
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
        <>
          {OrderType === 2 ? (
            <div style={{ padding: 8 }}>
              <Radio.Group
                onChange={e => {
                  setSelectedKeys(e.target.value)
                }}
                value={selectedKeys}
              >
                <Space direction='vertical'>
                  <Radio value={'due_days|desc'}>逾期天数降序</Radio>
                  <Radio value={'due_days|asc'}>逾期天数升序</Radio>

                  <Radio value={'due_amount|desc'}>逾期金额降序</Radio>
                  <Radio value={'due_amount|asc'}>逾期金额升序</Radio>

                  <Radio value={'due_number|desc'}>逾期次数降序</Radio>
                  <Radio value={'due_number|asc'}>逾期次数升序</Radio>
                </Space>
              </Radio.Group>
              <div style={{ marginTop: 8 }}>
                <Button
                  size='small'
                  type='text'
                  onClick={() => {
                    clearFilters()
                    confirm()
                    setOverdueFilter({ sort_name: '', sort: '' })
                    setTimeout(() => {
                      tableRef.current.reload()
                    }, 100)
                  }}
                  style={{ marginRight: 8, color: 'rgba(0, 0, 0, 0.25)' }}
                >
                  重置
                </Button>
                <Button
                  type='primary'
                  size='small'
                  onClick={() => {
                    confirm()
                    const [sort_name, sort] = selectedKeys.split('|')
                    setOverdueFilter({ sort_name, sort })
                    setTimeout(() => {
                      tableRef.current.reload()
                    }, 100)
                  }}
                >
                  确定
                </Button>
              </div>
            </div>
          ) : null}
        </>
      ),

      render: (text, record) => {
        const {
          overdue_amount,
          overdue_days,
          overdue_times,
          send_express_no,
          return_express_no,
          return_date,
          id,
          wx_trade_list,
          delivery_method,
          own_take_time,
          code,
          order_source,
          order_sn,
          after_sale_type,
          after_sale_type_text,
          support_amend_order,
          cancel_reason
        } = record

        return (
          <>
            <div>
              <b className={text === '售后拒绝' ? styles.danger_text_bold : ''}>{text}</b>
            </div>

            {after_sale_type ? (
              <div style={{ margin: '10px 0' }}>
                <Tag color={after_sale_type === 2 ? 'red' : 'purple'}>{after_sale_type_text}</Tag>
              </div>
            ) : null}

            {text === '已逾期' && overdue_times && overdue_amount && overdue_days ? (
              <>
                <div className={styles.danger_text}>次数：{overdue_times}</div>
                <div className={styles.danger_text}>
                  逾期{overdue_days}天（金额¥{overdue_amount}）
                </div>
              </>
            ) : null}

            {/* {text === '使用中' && return_date ? <div>归还日期：{return_date}</div> : null} */}

            {text === '待归还' && return_date ? <div>归还日期：{return_date}</div> : null}

            {send_express_no ? (
              <div style={{ display: 'flex', alignItems: 'center', flexShrink: 0 }}>
                <span>寄出快递：</span>
                <Button style={{ padding: '4px 0' }} type='link' onClick={() => checkExpress(1, id)}>
                  {send_express_no}
                </Button>
              </div>
            ) : null}

            {wx_trade_list?.length ? (
              <Tooltip placement='bottom' title={'微信小程序规定需要登录微信后台填写发货单号'} arrow>
                <Button
                  type='primary'
                  className={[styles.inner_option_button, styles.option_aqua_button]}
                  onClick={() => checkWXNo(wx_trade_list)}
                >
                  微信发货单号
                </Button>
              </Tooltip>
            ) : null}

            {return_express_no ? (
              <div>
                归还快递：
                <Button type='link' onClick={() => checkExpress(2, id)}>
                  {return_express_no}
                </Button>
              </div>
            ) : null}

            {text === '售后拒绝' && record.refuse_reason && (
              <Popover content={record.refuse_reason}>
                <div className={styles.reject_reason}>
                  <div>拒绝原因：</div>
                  <div className={styles.reject_reason_text}>{record.refuse_reason}</div>
                </div>
              </Popover>
            )}

            {text === '订单取消' && cancel_reason && (
              <Popover content={cancel_reason}>
                <div className={styles.reject_reason}>
                  <div>取消原因：</div>
                  <div className={styles.reject_reason_text}>{cancel_reason}</div>
                </div>
              </Popover>
            )}

            {text === '已发货' && platformType === 1 ? (
              <Button
                className={[styles.inner_option_button, styles.option_aqua_button]}
                style={{ margin: '0 10px' }}
                type='primary'
                onClick={() => handleUpdateExpress(record)}
              >
                修改物流
              </Button>
            ) : null}

            {text === '待提货' && platformType === 1 ? (
              <Button
                className={[styles.inner_option_button, styles.option_orgin_button]}
                type='primary'
                onClick={() => handleSelfPickup(record, false)}
              >
                提货验证
              </Button>
            ) : null}

            {/* {text === '使用中' && platformType === 1 ? ( */}
            {platformType === 1 && delivery_method && (text === '租赁中' || text === '使用中') ? (
              <>
                <div>
                  提货码：<span className={styles.blue_text}>{code}</span>
                </div>
                <div>验证时间：{own_take_time}</div>
              </>
            ) : null}
            {platformType === 1 && delivery_method && (text === '租赁中' || text === '使用中' || text === '已逾期') ? (
              <Button
                className={[styles.inner_option_button, styles.option_aqua_button]}
                type='primary'
                onClick={() => handleSelfPickup(record, true)}
              >
                查看凭证
              </Button>
            ) : null}

            {platformType === 1 &&
            text === '待支付' &&
            order_source === '微信' &&
            CheckOptionAuth('sign_other_pay_channel') ? (
              <Button type='primary' onClick={() => generateLink(order_sn)}>
                生成签约链接
              </Button>
            ) : null}

            <div>
              {renderOption(text, record, true)}
              {support_amend_order && platformType === 1 ? (
                <Button
                  className={[styles.inner_option_button, styles.option_orgin_button]}
                  type='primary'
                  onClick={() => handleRefillOrder(record)}
                >
                  补订单
                </Button>
              ) : null}
            </div>
          </>
        )
      }
    },
    {
      title: '订单备注',
      dataIndex: 'remarks',
      hideInSearch: true,
      align: 'center',
      width: 180,
      render: (text, record) => (
        <>
          {record.remarks ? (
            <div>
              <div>
                <div className={styles.remark_text}>{record.remarks}</div>
              </div>
              <Button
                className={[styles.inner_option_button, styles.option_aqua_button]}
                type='primary'
                onClick={() => checkRemark(record.id)}
              >
                备注记录
              </Button>
            </div>
          ) : (
            '/'
          )}
        </>
      )
    },
    {
      title: '归属来源',
      dataIndex: 'order_source',
      hideInSearch: true,
      width: 180,
      render: (text, record) => {
        const { plat_from_source, merchant_shop_name, salesman_name } = record
        return (
          <>
            <div>渠道：{plat_from_source}</div>
            <div>来源：{text}</div>
            {/* <div className={styles.color_text_aqua}>
              归属：
              {platformType ? salesman_name || '未分配' : merchant_shop_name || '未分配'}
            </div> */}
            <div className={styles.color_text_aqua}>
              归属：
              {merchant_shop_name || '未分配'}
            </div>
            <div className={styles.color_text_aqua}>
              审核员：
              {salesman_name || '未分配'}
            </div>
          </>
        )
      }
    },
    {
      title: '其他',
      dataIndex: 'orders_gain',
      hideInSearch: true,
      width: 280,
      render: (text, record) => {
        const { pay_type_name, rent_date, gain_flag, id, orders_gain } = record
        return (
          <>
            <div>支付方式：{pay_type_name}</div>
            <div>租期：{rent_date}</div>
            <div
              className={`${styles.other_info_block} ${
                orders_gain && orders_gain.length ? styles.color_text_blue : ''
              }`}
            >
              <div>增值服务：</div>
              <div>
                {orders_gain && orders_gain.length
                  ? orders_gain.map((i, idx) => (
                      <div key={idx}>
                        {i.gain_name}（¥{i.amount}）
                      </div>
                    ))
                  : '未购买'}
              </div>
            </div>
            <div>
              {gain_flag ? (
                <Popconfirm
                  title={`是否确认增值服务转入？`}
                  onConfirm={() => handleGainPay(id)}
                  okText='确认'
                  cancelText='取消'
                >
                  <Button className={styles.inner_option_button} type={'primary'}>
                    增值服务转入
                  </Button>
                </Popconfirm>
              ) : null}
            </div>
          </>
        )
      }
    },
    {
      title: '用户备注信息',
      dataIndex: 'buyer_remark',
      hideInSearch: true,
      align: 'center',
      width: 180,
      render: (text, record) => <>{record.buyer_remark || '/'}</>
    },
    {
      title: '操作',
      key: 'option',
      width: 150,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return [
          <a
            key='check'
            onClick={() => {
              checkOrderDetail(row.id)
            }}
          >
            详情
          </a>,
          <a
            key='remark'
            onClick={() => {
              triggerRemark(row.id, row.remarks)
            }}
          >
            备注
          </a>,
          row.deletable && !platformType ? (
            <Popconfirm
              key='delete'
              title='是否确定将该订单删除？'
              onConfirm={() => handleDeletOrder(row.id)}
              okText='确认'
              cancelText='取消'
            >
              <a key='delete' style={{ color: 'red' }}>
                删除订单
              </a>
            </Popconfirm>
          ) : row.refundable ? (
            <Popconfirm
              key='close'
              title='确认退款'
              onConfirm={() => handleRefund(row.id)}
              okText='确认退款'
              cancelText='取消'
              okType='danger'
            >
              <a key='refund' style={{ color: 'red' }}>
                退款
              </a>
            </Popconfirm>
          ) : row.closeable ? (
            <Popconfirm
              key='close'
              title='确认关闭订单'
              description='关闭后订单无法恢复，若有支付金额将在3个工作日内原路退回给用户，请确认是否继续。'
              onConfirm={() => handleCloseOrder(row.id)}
              okText='确认关闭'
              cancelText='取消'
              okType='danger'
            >
              <a key='close' style={{ color: 'red' }}>
                关闭订单
              </a>
            </Popconfirm>
          ) : null
        ]
      }
    },
    // searchForm
    {
      title: '所属渠道',
      dataIndex: 'plat_from_source',
      hideInTable: true,
      width: 180,
      valueType: 'select',
      valueEnum: new Map(channelList)
    },
    {
      title: '客户姓名',
      dataIndex: 'use_rec_name',
      hideInTable: true,
      width: 180
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      hideInTable: true,
      width: 180
    },
    {
      title: '审核人员',
      dataIndex: 'belong_mer_sale',
      hideInTable: true,
      width: 180,
      valueType: 'select',
      valueEnum: new Map(salesManList)
    },
    {
      title: '归属店铺',
      dataIndex: 'merchant_id',
      hideInTable: true,
      hideInSearch: userInfo.login_type === 'sub_shop',
      width: 180,
      valueType: 'select',
      valueEnum: new Map(shopList)
    },
    {
      title: '下单日期',
      dataIndex: 'created_date',
      hideInTable: true,
      // valueType: 'dateRange',
      width: 17,
      colSize: 1,
      valueType: 'dateTimeRange',
      render: (text, record) => <div>{record.created_date}</div>,
      search: {
        transform: value => {
          const [s, e] = value
          let res
          if (typeof s === 'string') {
            res = {
              start: value[0],
              end: value[1]
            }
            return res
          } else {
            res = {
              start: dayjs(value[0]['$d']).format('YYYY-MM-DD HH:mm:ss'),
              end: dayjs(value[1]['$d']).format('YYYY-MM-DD HH:mm:ss')
            }
          }
          return res
        }
      }
    },
    {
      title: '订单编号',
      dataIndex: 'order_sn',
      hideInTable: true,
      width: 180
    },
    {
      title: '订单来源',
      dataIndex: 'order_source',
      hideInTable: true,
      width: 180,
      valueType: 'select',
      valueEnum: new Map(currentChannelList)
    },
    {
      title: '公证状态',
      dataIndex: 'is_notary',
      hideInTable: true,
      width: 180,
      valueType: 'select',
      valueEnum: new Map([
        [1, '已公证'],
        [0, '未公证']
      ])
    }
  ]

  const billColumns = [
    {
      title: '订单信息',
      dataIndex: 'order_sn',
      hideInSearch: true,
      width: 300,
      render: (text, record) => (
        <>
          <div className={styles.order_tag_group}>
            {record.life_type === 2 ? (
              <div>
                <Tag color='green'>自建订单</Tag>
              </div>
            ) : (
              <div>
                <Tag color='blue'>普通订单</Tag>
              </div>
            )}

            {record.xz_flag === 1 && (
              <div>
                <Tag color='purple'>续租</Tag>
              </div>
            )}

            {!!record.is_notary && (
              <div>
                <Tag color='red'>已公证</Tag>
              </div>
            )}
          </div>

          <div>
            <b>订单编号：{text}</b>
          </div>
          <div>下单时间：{record.created_at}</div>
          {record.xz_flag === 1 && (
            <div
              style={{ color: '#1677ff', cursor: 'pointer' }}
              onClick={() => checkOrderDetail(record.original_order_id)}
            >
              原订单 : {record.original_no}
            </div>
          )}
        </>
      )
    },
    {
      title: '用户资料',
      dataIndex: 'cert_name',
      hideInSearch: true,
      width: 280,
      render: (text, record) => {
        const { cert_no, user_id, gender, age, face_identify, mobile, show_cert_no, show_mobile, id } = record

        return (
          <>
            {text && cert_no ? (
              <div>
                <b>
                  {text}（{cert_no}）
                </b>
                {show_cert_no ? (
                  <EyeInvisibleTwoTone
                    className={styles.clickable_icon}
                    onClick={() => triggerPrivacy(id, 'cert_no')}
                  />
                ) : (
                  <EyeTwoTone className={styles.clickable_icon} onClick={() => triggerPrivacy(id, 'cert_no', true)} />
                )}
              </div>
            ) : (
              <p className={styles.grey}>未实名认证</p>
            )}
            <div>
              <b>
                用户ID：
                <a onClick={e => checkUser(user_id)}>{user_id}</a>
              </b>
            </div>
            <div>
              <span>
                <span>{gender && age ? `${gender}（${age}岁）  ` : `-   `}</span>
                人脸识别：
                <svg className='icon' aria-hidden='true'>
                  <use xlinkHref={face_identify ? '#icon-bailongsuccessful' : '#icon-bailongfailed'}></use>
                </svg>
              </span>
            </div>
            <div>
              {`${mobile} ` || '未获取手机号'}
              {mobile ? (
                show_mobile ? (
                  <EyeInvisibleTwoTone className={styles.clickable_icon} onClick={() => triggerPrivacy(id, 'mobile')} />
                ) : (
                  <EyeTwoTone className={styles.clickable_icon} onClick={() => triggerPrivacy(id, 'mobile', true)} />
                )
              ) : null}
            </div>
          </>
        )
      }
    },
    {
      title: '支付状态',
      dataIndex: 'pay_status',
      hideInSearch: true,
      width: 240,
      render: (text, record) => {
        const { total_price, pay_money, rec_time, due_amount, due_days } = record
        return (
          <div>
            {payStatusMap[text] ? (
              <div style={{ color: payStatusMap[text].color }}>{payStatusMap[text].text}</div>
            ) : null}

            {text !== 4 ? <div>本期金额：¥{pay_money}</div> : null}
            {text === 4 ? (
              <div style={{ color: '#FF0000' }}>
                逾期{due_days}天（金额¥{due_amount}）
              </div>
            ) : null}
            <div>总租金：¥{total_price}</div>
            {text === 2 || text === 3 ? <div>支付时间：{rec_time}</div> : null}
          </div>
        )
      }
    },
    {
      title: '账单',
      dataIndex: 'lease_time',
      hideInSearch: true,
      width: 180,
      render: (text, record) => {
        const { lease_term, dead_time } = record
        return (
          <div>
            <div>当前：第{text}期</div>
            <div>总期数：{lease_term}期</div>
            <div>账单日：{dead_time}</div>
          </div>
        )
      }
    },
    {
      title: '归属来源',
      dataIndex: 'order_source',
      hideInSearch: true,
      width: 180,
      render: (text, record) => {
        const { plat_from_source, merchant_shop_name, salesman_name } = record
        return (
          <>
            <div>渠道：{plat_from_source}</div>
            <div>来源：{text}</div>
            {/* <div className={styles.color_text_aqua}>
              归属：
              {platformType ? salesman_name || '未分配' : merchant_shop_name || '未分配'}
            </div> */}
            <div className={styles.color_text_aqua}>
              归属：
              {merchant_shop_name || '未分配'}
            </div>
            <div className={styles.color_text_aqua}>
              审核员：
              {salesman_name || '未分配'}
            </div>
          </>
        )
      }
    },
    {
      title: '操作',
      key: 'option',
      width: 150,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return [
          <a
            key='check'
            onClick={() => {
              checkOrderDetail(row.id)
            }}
          >
            详情
          </a>
        ]
      }
    },
    // searchForm
    {
      title: '所属渠道',
      dataIndex: 'promotion_id',
      hideInTable: true,
      width: 180,
      valueType: 'select',
      valueEnum: new Map(channelList)
    },
    {
      title: '客户姓名',
      dataIndex: 'user_name',
      hideInTable: true,
      width: 180
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      hideInTable: true,
      width: 180
    },
    {
      title: '归属店铺',
      dataIndex: 'merchant_id',
      hideInTable: true,
      hideInSearch: userInfo.login_type === 'sub_shop',
      width: 180,
      valueType: 'select',
      valueEnum: new Map(shopList)
    },
    {
      title: '审核人员',
      dataIndex: 'belong_mer_sale',
      hideInTable: true,
      width: 180,
      valueType: 'select',
      valueEnum: new Map(salesManList)
    },
    {
      title: '账单日',
      dataIndex: 'bill_date',
      hideInTable: true,
      width: 200,
      colSize: 1,
      valueType: 'dateRange',
      fieldProps: {
        disabledDate: (current, { from, type }) => {
          if (from) {
            const minDate = from.add(-29, 'days')
            const maxDate = from.add(29, 'days')

            switch (type) {
              case 'year':
                return current.year() < minDate.year() || current.year() > maxDate.year()

              case 'month':
                return getYearMonth(current) < getYearMonth(minDate) || getYearMonth(current) > getYearMonth(maxDate)

              default:
                return Math.abs(current.diff(from, 'days')) >= 30
            }
          }

          return false
        }
      },
      search: {
        transform: value => {
          const [s, e] = value
          let res
          if (typeof s === 'string') {
            res = {
              start: value[0],
              end: value[1]
            }
            return res
          } else {
            res = {
              start: dayjs(value[0]['$d']).format('YYYY-MM-DD'),
              end: dayjs(value[1]['$d']).format('YYYY-MM-DD')
            }
          }
          return res
        }
      }
    }
  ]

  useEffect(() => {
    if (OrderType === 6) {
      setColumns(billColumns)
    } else {
      setColumns(originColumns)
    }
  }, [shopList, salesManList, currentChannelList, channelList, OrderType])

  return (
    <>
      <ProTable
        actionRef={tableRef}
        formRef={proTableFormRef}
        rowSelection={
          rowSelectable
            ? {
                selectedRowKeys: currentSelectedRowKeys,
                onChange: handleSelectChange
              }
            : false
        }
        request={async params => {
          setIsLoading(true)
          if (OrderType === 6) {
            const param = {
              page: params.current,
              page_size: params.pageSize,
              ...params,
              bill_date_start: params.start,
              bill_date_end: params.end
            }
            if (tabActiveKey && tabActiveKey !== 'all_bill_number' && tabActiveKey !== 'all_order') {
              const item = originTabs.find(i => i.key === tabActiveKey)
              param.pay_status = item.status
            }

            setCurrentPage(params.current)
            setPageSize(params.pageSize)
            const res = await GetExpiredBillsData(param)
            await getBillsCount(params)

            setIsLoading(false)
            const { data, total } = res

            return {
              data: data,
              success: true,
              total: total
            }
          } else {
            const filters = {
              plat_from_source: params.plat_from_source,
              use_rec_name: params.use_rec_name,
              tel: params.tel,
              merchant_id: params.merchant_id,
              order_sn: params.order_sn,
              type: OrderType,
              belong_mer_sale: params.belong_mer_sale,
              platform_type: platformType ? 2 : 1,
              order_source: params.order_source,
              is_notary: params.is_notary,
              // 逾期筛选项
              sort_name: overdueFilter.sort_name,
              sort: overdueFilter.sort,
              created_at_start: params.start,
              created_at_end: params.end,
              // 去重
              is_distinct: isDistinct ? 1 : 0
            }

            setCurrentSelectedRowKeys([])

            const param = {
              page: params.current,
              page_size: params.pageSize,
              ...filters
            }
            if (tabActiveKey && tabActiveKey !== 'all_order') {
              const item = originTabs.find(i => i.key === tabActiveKey)
              console.log('originTabs', item)
              param.status = item.status
              param.special_day_tips = item.special_day_tips
              param.in_after_sale = item.in_after_sale
              param.become_due = item.become_due
            }

            setCurrentPage(params.current)
            setPageSize(params.pageSize)
            const res = sellType ? await EcommerceOrderList(param) : await GetBackendOrderList(param)
            await getOrderCount(filters)

            setIsLoading(false)

            const { data, total } = res

            data.forEach((i, idx) => {
              if (privacyData[i.id]) {
                data[idx] = {
                  ...i,
                  ...privacyData[i.id]
                }
              }
            })
            return {
              data: data,
              success: true,
              total: total
            }
          }
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        headerTitle={
          <>
            {haveSubMerchant && batchAllocationShow ? (
              <Button
                onClick={batchDistribution}
                disabled={!currentSelectedRowKeys.length}
                style={!currentSelectedRowKeys.length ? null : { color: '#165DFF', borderColor: '#165DFF' }}
              >
                批量分配
              </Button>
            ) : null}
            {OrderType === 2 ? (
              <Alert banner message={`逾期金额总计:¥ ${overdueAmount}`} type='warning' showIcon />
            ) : null}
          </>
        }
        rowKey='id'
        scroll={{ x: 1300 }}
        columns={columns}
        toolBarRender={() =>
          OrderType === 6
            ? []
            : [
                <Space key={Math.random().toString()}>
                  <Tooltip placement='top' title='根据用户ID进行去重'>
                    <QuestionCircleOutlined />
                  </Tooltip>
                  <Switch
                    onChange={onIsDistinctSwitchChange}
                    defaultChecked={isDistinct}
                    checkedChildren='用户去重'
                    unCheckedChildren='用户去重'
                    loading={isLoading}
                  />
                </Space>,

                batchAllocationShow ? (
                  <Button
                    key={Math.random().toString()}
                    disabled={batchAllocationFlag}
                    onClick={getBatchAllocationList}
                    icon={<AuditOutlined />}
                  >
                    分配审核
                  </Button>
                ) : null,

                CheckOptionAuth('exportOrderData') ? (
                  <Popconfirm
                    key='export'
                    title='确认导出订单?'
                    description='确认导出订单后，将在导出中心生成订单数据文件，请在导出中心下载。'
                    onConfirm={() => handleExportTable()}
                    okText='确认导出'
                    cancelText='取消'
                    okType='primary'
                  >
                    <Button icon={<DownloadOutlined />}>导出数据</Button>
                  </Popconfirm>
                ) : null
              ]
        }
        search={{
          defaultCollapsed: false,
          labelWidth: 75,
          span: 6
        }}
        toolbar={{
          multipleLine: true,
          tabs: {
            onChange: key => handleTabActive(key),
            activeKey: tabActiveKey,
            items: tabsList
          }
        }}
      />

      {/* 添加备注弹窗 */}
      <Modal
        title='添加备注'
        destroyOnClose
        okText='保存'
        open={showRemarkModal}
        onCancel={triggerRemark}
        onOk={handleRemarkOk}
        bodyStyle={{ paddingBottom: '10px' }}
      >
        <TextArea
          placeholder='请输入备注内容'
          onChange={onInputRemark}
          // maxLength={50}
          showCount={true}
          value={remarkNote}
          style={{ height: 120 }}
        ></TextArea>
      </Modal>

      {/* 查看备注弹窗 */}
      <Modal
        title='备注记录'
        destroyOnClose
        open={showCheckRemarkModal}
        onCancel={() => setShowCheckRemarkModal(false)}
        footer={null}
        bodyStyle={{ paddingBottom: '10px' }}
      >
        <List
          itemLayout='horizontal'
          dataSource={remarkList}
          renderItem={item => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar size='small' icon={<UserOutlined />} />}
                title={
                  <div className={styles.remark_title}>
                    <span>{item.operate_user || '未记录用户'}</span>
                    <span>{item.created_at}</span>
                  </div>
                }
                description={item.content}
              />
            </List.Item>
          )}
        />
      </Modal>

      {/* 查看物流弹窗 */}
      <Modal
        title='物流详情'
        destroyOnClose
        open={showExpressModal}
        onCancel={() => setShowExpressModal(false)}
        footer={null}
        width={680}
        bodyStyle={{ paddingBottom: '10px' }}
      >
        <div className={styles.express_modal}>
          <div className={styles.express_title}>
            <div>快递公司：{expressData.company_name}</div>
            <div>快递单号：{expressData.number}</div>
          </div>
          <Timeline mode='left' items={expressData.timeLine} />
        </div>
      </Modal>

      {/* 去处理售后弹窗 */}
      <Modal
        title='售后处理'
        destroyOnClose
        open={showSolveAfterModal}
        width={580}
        onCancel={() => setShowSolveAfterModal(false)}
        bodyStyle={{ paddingBottom: '10px' }}
        footer={
          <>
            <Button type={'primary'} danger onClick={() => setShowRefuseAfterSalesModal(true)}>
              拒绝
            </Button>
            <Popconfirm
              title='是否确定同意该用户售后申请？'
              onConfirm={handleAfterSalesAgree}
              okText='确认'
              cancelText='取消'
            >
              <Button type={'primary'}>同意</Button>
            </Popconfirm>
          </>
        }
      >
        <Alert
          banner
          showIcon
          message='售后申请同意后不可撤销，若有支付金额将在3个工作日内原路退回给用户'
          type='info'
        />
        <div className={styles.modal_reason_content}>
          <div className={styles.modal_reason_title}>
            <span>售后类型 :</span>
            <span className={styles.modal_reason_text}> {currentOrderInfo.after_sale_type_text} </span>
          </div>
          <p>用户原因描述 :</p>
          <TextArea rows={4} disabled={true} value={userAfterSalesReason} />
        </div>
      </Modal>

      {/* 拒绝售后弹窗 */}
      <Modal
        title='拒绝原因'
        destroyOnClose
        okText='保存'
        open={showRefuseAfterSalesModal}
        onCancel={() => {
          setShowRefuseAfterSalesModal(false)
          setCurrentRefuseAfterReason(null)
          setRefuseOwnAmount(null)
        }}
        onOk={handleRefuseAfterSalesOK}
        bodyStyle={{ paddingBottom: '10px' }}
      >
        {currentOrderInfo.after_sale_type === 1 ? (
          <TextArea
            placeholder='请输入拒绝理由'
            onChange={onInputRefuseAfterSales}
            maxLength={50}
            showCount={true}
            style={{ height: 120 }}
          />
        ) : (
          <div>
            <Form.Item label='拒绝理由'>
              <Select
                placeholder='请选择拒绝理由'
                onChange={handleSelectRefuseReason}
                options={[
                  {
                    value: 'USER_OWE_MONEY',
                    label: '用户账户存在欠费订单'
                  },
                  {
                    value: 'USER_IN_SERVICE',
                    label: '用户有进行的订单'
                  }
                ]}
              />
            </Form.Item>
            {currentRefuseAfterReason === 'USER_OWE_MONEY' ? (
              <Form.Item label='拒绝理由'>
                <InputNumber
                  min={0}
                  value={refuseOwnAmount}
                  addonAfter={'元'}
                  placeholder='请输入'
                  onChange={e => setRefuseOwnAmount(e)}
                />
              </Form.Item>
            ) : null}
          </div>
        )}
      </Modal>

      {/* 发货弹窗 */}
      <Modal
        title='发货信息'
        destroyOnClose
        okText='发货'
        open={deliveryModal}
        onCancel={triggerDelivery}
        onOk={handleDelivery}
        bodyStyle={{ paddingTop: '20px' }}
      >
        <Form.Item labelCol={3} wrapperCol={20} label='物流公司' required>
          <Select
            onChange={e => changeDeliveryData('expressName', e)}
            placeholder='请选择物流公司'
            options={expressList}
          ></Select>
        </Form.Item>
        <Form.Item labelCol={3} wrapperCol={20} required label='物流单号'>
          <Input onChange={e => changeDeliveryData('expressNo', e.target.value)} placeholder='请输入物流编号'></Input>
        </Form.Item>
      </Modal>

      {/*分配审核弹窗*/}
      <Modal
        title={'分配审核'}
        mask
        open={batchAllocationModal}
        onCancel={() => setBatchAllocationModal(false)}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        destroyOnClose
        maskClosable={false}
        footer={
          <>
            <Button onClick={() => setBatchAllocationModal(false)}>取消</Button>
            <Button type={'primary'} onClick={handleConfirmBatchAllocation}>
              确认
            </Button>
          </>
        }
      >
        <Form form={batchAllocationFormRef} onFinish={onForceAFinished} name='forceAllocationForm' {...formItemLayout}>
          <Form.Item
            name='personnel_name'
            label='人员名称'
            rules={[{ required: true, message: '请选择需要分配的人员！' }]}
          >
            <Select allowClear onChange={checkAllocation} options={allocationList} placeholder='请选择' />
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看微信单号弹窗 */}
      <Modal
        title='查看微信单号'
        destroyOnClose
        open={showWXNoModal}
        onCancel={() => setShowWXNoModal(false)}
        footer={null}
        centered
        bodyStyle={{ paddingBottom: '10px' }}
      >
        <List
          itemLayout='horizontal'
          dataSource={[
            {
              transaction_id: '微信单号',
              created_at: '创建时间'
            }
          ]}
          renderItem={item => (
            <List.Item>
              <List.Item.Meta
                title={
                  <div className={styles.remark_title}>
                    <span>{item.transaction_id}</span>
                    <span>{item.created_at}</span>
                  </div>
                }
              />
            </List.Item>
          )}
        />
        <List
          itemLayout='horizontal'
          dataSource={wxTradeList}
          renderItem={item => (
            <List.Item>
              <List.Item.Meta
                title={
                  <div className={styles.remark_title}>
                    <span>{item.transaction_id}</span>
                    <span>{item.created_at}</span>
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Modal>

      {/*提货弹窗*/}
      <Modal
        title={isView ? '查看凭证' : '提货验证'}
        mask
        open={showPickupModal}
        // open={true}
        onCancel={() => setShowPickupModal(false)}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        destroyOnClose
        maskClosable={false}
        footer={
          isView ? (
            <Button type='primary' onClick={() => setShowPickupModal(false)}>
              关闭
            </Button>
          ) : (
            <>
              <Button onClick={() => setShowPickupModal(false)}>取消</Button>
              <Popconfirm
                okText='确认提交'
                title='确认提交验证'
                description={
                  <>
                    <div>请仔细核对提货码，验证成功后订单状态变更为【已收货】</div>
                    <div>且不可变更，请问是否要提交验证</div>
                  </>
                }
                onConfirm={checkPickup}
              >
                <Button type={'primary'}>提交验证</Button>
              </Popconfirm>
            </>
          )
        }
      >
        {showPickupModal ? (
          <Card title={null} className={styles.pickupModal} bordered={false} bodyStyle={{ padding: 0 }}>
            <div className={styles.pickup_info_wrapper}>
              <div className={styles.pickup_info_header}>
                <div className={styles.header_title}>提货信息</div>
                <div className={styles.product_info}>
                  <div className={styles.product_img}>
                    <Image width={72} src={currentOrderInfo.goods_pic} />
                  </div>
                  <div className={styles.product_info_detail}>
                    <div className={styles.product_title}>{currentOrderInfo.goods_name}</div>
                    <div>规格：{currentOrderInfo.attr_value}</div>
                    <div>数量：x1</div>
                  </div>
                </div>
              </div>
              <Space direction='vertical' style={{ width: '100%' }} size='middle'>
                {pickupInfoList.map(i => {
                  const {
                    label,
                    parentNode,
                    needJoin,
                    valueIndex,
                    needCopy,
                    checkPrivacy,
                    passKey,
                    joinChar,
                    getValueFromEvent
                  } = i
                  let value
                  const checkKey = 'show_' + passKey
                  if (getValueFromEvent) {
                    value = getValueFromEvent(currentOrderInfo)
                  } else if (needJoin) {
                    value = [...valueIndex]
                      .map(d => (parentNode ? currentOrderInfo[parentNode][d] : currentOrderInfo[d]))
                      .join(joinChar || '')
                  } else {
                    value = parentNode
                      ? currentOrderInfo[parentNode][valueIndex] || '-'
                      : currentOrderInfo[valueIndex] || '-'
                  }
                  if (checkPrivacy) {
                    value = currentOrderInfo[checkKey] ? currentOrderInfo[passKey] : value
                  }

                  return (
                    <div className={styles.pickup_info_line} key={label}>
                      <div className={styles.pickup_info_label}>{label}</div>
                      <div className={styles.pickup_info_value}>
                        {value}
                        {needCopy ? (
                          <CopyOutlined className={styles.text_icon} onClick={() => copyToClip(value)} />
                        ) : null}
                        {checkPrivacy ? (
                          currentOrderInfo[checkKey] ? (
                            <EyeInvisibleTwoTone
                              className={styles.text_icon}
                              onClick={() => triggerPrivacy(currentOrderInfo.id, 'consignee_tel', false, true)}
                            />
                          ) : (
                            <EyeTwoTone
                              className={styles.text_icon}
                              onClick={() => triggerPrivacy(currentOrderInfo.id, 'consignee_tel', true, true)}
                            />
                          )
                        ) : null}
                      </div>
                    </div>
                  )
                })}
              </Space>
            </div>
          </Card>
        ) : null}

        <Form form={selfPickupFormRef} onFinish={handleSubmitPickup} name='selfPickup'>
          <Form.Item
            name='code'
            label='提货码'
            rules={isView ? [] : [{ required: true, message: '请输入用户自提订单提货凭证页提货码进行验证！' }]}
            help={isView ? '' : '请告知用户打开订单-->点击【提货】打开自提订单提货凭证页并出示凭证'}
          >
            <Input allowClear placeholder='请输入用户自提订单提货凭证页提货码进行验证' disabled={isView} />
          </Form.Item>
          <Form.Item
            label='凭证上传'
            name='voucher'
            rules={isView ? [] : [{ required: true, message: '请上传凭证！' }]}
            valuePropName='fileList'
            multiple={true}
            getValueFromEvent={e => formatUploadValue(e)}
            help={isView ? '' : '请上传用户手持身份证正面照片，确保图像清晰可辨'}
          >
            <Upload
              maxCount={9}
              formProps={{
                name: 'file',
                listType: 'picture-card'
              }}
              disabled={isView}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/*优惠券信息 couponInfo*/}
      <Modal
        title='优惠券信息'
        mask
        zIndex={9999}
        open={showCouponModal}
        // open={true}
        onCancel={() => setShowCouponModal(false)}
        width={640}
        destroyOnClose
        maskClosable={false}
        footer={
          <>
            <Button onClick={() => setShowCouponModal(false)}>关闭</Button>
          </>
        }
      >
        {showCouponModal ? (
          <Card title={null} className={styles.couponModal} bordered={false} bodyStyle={{ padding: 0 }}>
            <div className={styles.coupon_wrapper}>
              <div className={styles.coupon_header}>
                <div className={styles.product_info}>
                  <div className={styles.product_img}>
                    <Image width={72} src={currentOrderInfo.goods_pic} />
                  </div>
                  <div className={styles.product_info_detail}>
                    <div className={styles.product_title}>{currentOrderInfo.goods_name}</div>
                    <div>规格：{currentOrderInfo.attr_value}</div>
                    <div>数量：x1</div>
                  </div>
                </div>
                <Space direction='vertical' style={{ width: '100%' }} size='middle'>
                  <div className={styles.coupon_line}>
                    <div className={styles.coupon_label}>订单编号</div>
                    <div className={styles.coupon_value}>
                      {currentOrderInfo.order_sn}
                      <CopyOutlined
                        className={styles.text_icon}
                        onClick={() => copyToClip(currentOrderInfo.order_sn)}
                      />
                    </div>
                  </div>
                  <div className={styles.coupon_line}>
                    <div className={styles.coupon_label}>创建时间</div>
                    <div className={styles.coupon_value}>{currentOrderInfo.created_at}</div>
                  </div>
                </Space>
              </div>
              <Space direction='vertical' style={{ width: '100%' }} size='middle'>
                {couponInfo.map(i => {
                  const { coupon_type, coupon_id, coupon_name, discount_content, amount, created_at } = i
                  return (
                    <div className={styles.coupon_item} key={coupon_id}>
                      <div>
                        <b>{coupon_type}</b>
                      </div>
                      <div className={styles.coupon_line}>
                        <div className={styles.coupon_label}>使用时间</div>
                        <div className={styles.coupon_value}>{created_at}</div>
                      </div>
                      <div className={styles.coupon_line}>
                        <div className={styles.coupon_label}>券码ID</div>
                        <div className={styles.coupon_value}>{coupon_id}</div>
                      </div>
                      {discount_content ? (
                        <div className={styles.coupon_line}>
                          <div className={styles.coupon_label}>优惠内容</div>
                          <div className={styles.coupon_value}>{discount_content}</div>
                        </div>
                      ) : null}
                      <div className={styles.coupon_line}>
                        <div className={styles.coupon_label}>实际优惠金额</div>
                        <div className={styles.coupon_value} style={{ color: '#FF0000' }}>
                          -¥{amount}
                        </div>
                      </div>
                    </div>
                  )
                })}
              </Space>
            </div>
          </Card>
        ) : null}
      </Modal>

      {/*订单分配弹窗*/}
      <Modal
        title={'订单分配'}
        mask
        open={distributionModal}
        onCancel={() => setDistributionModal(false)}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        destroyOnClose
        maskClosable={false}
        footer={
          <>
            <Button onClick={() => setDistributionModal(false)}>取消</Button>
            {distributionList.length === 1 ? (
              <Popconfirm
                title='不分配直接进入审核'
                icon={<ExclamationCircleFilled style={{ color: '#165DFF' }} />}
                description='选择直接审核将直接分配给当前账号直接进入审核流程，归属为当前账号及所属店铺，是否确定继续？'
                onConfirm={() => checkOrderDetail(distributionList[0])}
                okText='确认'
                cancelText='取消'
              >
                <Button style={{ color: '#165DFF', borderColor: '#165DFF' }} onClick={null}>
                  不分配直接审核
                </Button>
              </Popconfirm>
            ) : null}
            <Button type={'primary'} onClick={distributionFormRef.submit}>
              确认分配
            </Button>
          </>
        }
      >
        <Form form={distributionFormRef} onFinish={handleDistribute} {...formItemLayout}>
          <Form.Item
            name='merchant_id'
            label='分配店铺'
            rules={[{ required: true, message: '请选择需要分配的店铺！' }]}
          >
            <Select options={subMerchantList} placeholder='请选择' onChange={handleSelectSubMerchant}></Select>
          </Form.Item>
          {auditorList && auditorList.length ? (
            <Form.Item
              name='to_user_id'
              rules={[{ required: true, message: '请选择需要分配的人员！' }]}
              label='审核员'
              help='未分配审核员的订单将需要在该店铺后台分配审核员'
            >
              <Select allowClear placeholder='请选择' options={auditorList}></Select>
            </Form.Item>
          ) : null}
        </Form>
      </Modal>

      {/*弹窗*/}
      <Modal
        title={'补订单'}
        mask
        open={refillorderModal}
        onCancel={cancelRefillorder}
        destroyOnClose
        maskClosable={false}
        okText={refillStep ? '重新生成' : '生成付款码'}
        onOk={generateQr}
      >
        <Form name='refillorder' form={refillorderForm}>
          <Form.Item name='id' label='增值服务' rules={[{ required: true, message: '请选择要补充的增值服务' }]}>
            <Checkbox.Group style={{ display: 'block' }} onChange={handleRefillChange}>
              {gainList.map(item => {
                return (
                  <div key={item.id}>
                    <div className={styles.radio_line}>
                      <Checkbox
                        value={item.id}
                        disabled={Boolean(currentOrderInfo.orders_gain.find(i => i.associate_id === item.id))}
                      >
                        {item.name}
                        {item.type === 1 ? `（¥${item.price}）` : item.type === 3 ? `（租金${item.price}%）` : null}
                      </Checkbox>
                    </div>
                    <br />
                    {item.type === 2 && refillGainList.includes(item.id) ? (
                      <div style={{ paddingLeft: '20px' }}>
                        <Form.Item label='价格' name='price' rules={[{ required: true }]}>
                          <InputNumber
                            prefix={'¥'}
                            precision={2}
                            className={styles.input_number_item}
                            onChange={e => handleChangeRefillOrderPrice(item.id, e)}
                            bordered={false}
                          />
                        </Form.Item>
                      </div>
                    ) : null}
                  </div>
                )
              })}
            </Checkbox.Group>
          </Form.Item>
        </Form>

        {refillStep ? (
          <Card bordered={false} title='付款二维码'>
            <div className={styles.refillorder_content}>
              <QRCode id='qrCode' value={refillQrData.qr_code} size={200} fgColor='#000000' />
              <div className={styles.highlight_price}>¥{refillQrData.total_pay}</div>
              <div className={styles.info_line}>
                <img src={alipayIcon}></img>请将二维码发给客户扫码支付
              </div>
              <div className={styles.info_line}>创建时间：{refillQrData.created_at}</div>
              <div className={styles.highlight_info}>有效期3小时，过期需要重新生成</div>

              <Button type='primary' onClick={downloadQr}>
                保存二维码图片到本地
              </Button>
            </div>
          </Card>
        ) : null}
      </Modal>
    </>
  )
}
